package com.greendragon.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang.xwork.StringUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author wulibin, exceptsky@gmail.com, 2011-9-11 下午12:11:55
 * 
 */
public class EncryptionUtil {
	/**
	 * encode a string with md5
	 * 
	 * @param message
	 */
	public static String encodeMD5(String message) {
		if(StringUtils.isEmpty(message)){
			return "";
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(message.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			return number.toString(16);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	/*
	 * char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	 * 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] strTemp = s.getBytes();
	 * MessageDigest mdTemp = MessageDigest.getInstance("MD5");
	 * mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length;
	 * char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) {
	 * byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] =
	 * hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) {
	 * 
	 * return null; }
	 */

	public static String getBASE64(byte[] b) {
		String s = null;
		if (b != null) {
			s = new BASE64Encoder().encode(b);
		}
		return s;
	}

	public static byte[] getFromBASE64(String s) {
		byte[] b = null;
		if (s != null) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				b = decoder.decodeBuffer(s);
				return b;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return b;
	}
}
